﻿// -----------------------------------------------------------------------
// <copyright file="VisitationRequestPresenter.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace AFS.VisitationRequestTool.Addin
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Office.Interop.Outlook;
    using AFS.VisitationRequestTool.Addin.Entities;
    using AFS.VisitationRequestTool.Addin.Components;
    using System.Windows.Forms;
    using AFS.VisitationRequestTool.Addin.Common;
    using AFS.VisitationRequestTool.Addin.Variables;
    using AFS.VisitationRequestTool.Addin.XML;
    using AFS.VisitationRequestTool.Addin;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    /// TODO: This is currently bad design. View components (RequestDetailsFormRegion and Ribbon) currently part of presenter, with no seperation of concerns (can't reuse for another view, like mobile UI). 
    /// View should be just be passing model to presenter for action result (pending VisitationRequest entity). No way to unit test when VSTO related component coupled with business logic.
    /// If want to do it, do it right: http://magenic.com/Blog/MVPPatternforOutlook
    public class VisitationRequestPresenter
    {
        // Should be referencing Model "backend stores": SharePoint and Outlook/Exchange and Model (VisitationRequest entity). Not UI components.  
        // Controller should be forwarding application of business logic to model and reply with valid or invalid results. Then view handles messaging to user.
        RequestDetailsFormRegion requestDetailsForm;
        Ribbon uploadToSharePointRibbon;
        //ProgressForm currentProgressForm;

        // public event Microsoft.Office.Tools.Outlook.FormRegionInitializingEventHandler FormRegionInitializing;

        public VisitationRequestPresenter()
        {
            Inspector activeInspector = Globals.ThisAddIn.Application.ActiveInspector();
            new VisitationRequestPresenter(activeInspector);
            Logger.Verbose("No params entered");
        }

        public VisitationRequestPresenter(Inspector activeInspector)
        {
            Logger.Verbose("activeInspector params entered");

            if (activeInspector == null)
            {
                if (Globals.ThisAddIn.Application.Inspectors.Count > 0)
                    activeInspector = Globals.ThisAddIn.Application.Inspectors[0];
                else
                {
                    Logger.Error("Active inspector null in VisitationRequestPresenter constructor");
                    throw new System.Exception(ErrorMessages.ProgramException);
                }
            }

            try
            {
                WindowFormRegionCollection formRegions = Globals.FormRegions[activeInspector];
                new VisitationRequestPresenter(formRegions.AFSRequestDetailsForm);
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex.ToString());
                MessageBox.Show(PopUpText.ErrorProgramTryAgain);
            }

        }

        public VisitationRequestPresenter(RequestDetailsFormRegion requestDetails)
        {
            Logger.Verbose("requestDetails params entered");
            this.requestDetailsForm = requestDetails;
        }

        public void SaveItemDetails()
        {
            Logger.Verbose("Entered");
            this.requestDetailsForm.SaveRequestDetailsToLocalOutlookItemProperties();
        }

        public bool CancelInvite(MeetingItem meetingItem)
        {
            Logger.Verbose("meetingItem params entered");
            Persons meetingRecipients = FillRecipients(meetingItem);
            return CancelInviteResult(meetingRecipients);
        }

        public bool CancelInvite(AppointmentItem appointmentItem)
        {
            Logger.Verbose("appointmentItem params entered");
            Persons meetingRecipients = FillRecipients(appointmentItem);
            return CancelInviteResult(meetingRecipients);
        }

        private bool CancelInviteResult(Persons meetingRecipients)
        {
            Logger.Verbose("meetingRecipients params entered");

            bool cancel = false;

            try
            {
                // meetingItem.ForceUpdateToAllAttendees = true;

                if (meetingRecipients.ContainsACN)
                {
                    CustomDialog customDialog = new CustomDialog();
                    customDialog.OkButtonText = PopUpText.MessageBoxTextStatusOK;
                    customDialog.CancelButtonText = PopUpText.MessageBoxTextStatusCancel;

                    DialogResult dialogResult = customDialog.ShowDialog();

                    if (dialogResult == DialogResult.Cancel)
                    {
                        cancel = true;
                    }
                    else
                    {
                        cancel = false;
                    }

                    customDialog.Close();
                }
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex.ToString());
                MessageBox.Show(PopUpText.ErrorProgramTryAgain);
            }
            finally
            {
                // TODO: any COM cleanup?
            }

            return cancel;
        }

        private Persons FillRecipients(MeetingItem meetingItem)
        {
            Persons meetingRecipients = new Persons();
            // Checking if there's an incomplete AFS visitation request pending submission

            if (requestDetailsForm == null)
            {
                requestDetailsForm = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveInspector()].AFSRequestDetailsForm;
            }

            if (this.requestDetailsForm.txtFileName_Hidden.TextLength == 0 &&
                meetingItem != null) // && meetingItem.MeetingStatus != OlMeetingStatus.olMeetingCanceled)
            {
                foreach (Recipient recipient in meetingItem.Recipients)
                    if (recipient.Address != meetingItem.Session.CurrentUser.Address)
                    {
                        meetingRecipients.Add(new MeetingRecipient(recipient));
                    }
            }

            return meetingRecipients;
        }

        private Persons FillRecipients(AppointmentItem appointmentItem)
        {
            Persons meetingRecipients = new Persons();
            // Checking if there's an incomplete AFS visitation request pending submission

            if (requestDetailsForm == null)
            {
                requestDetailsForm = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveInspector()].AFSRequestDetailsForm;
            }

            if (this.requestDetailsForm.txtFileName_Hidden.TextLength == 0
                && appointmentItem != null) // && meetingItem.MeetingStatus != OlMeetingStatus.olMeetingCanceled)
            {
                foreach (Recipient recipient in appointmentItem.Recipients)
                {
                    if (recipient.Address != appointmentItem.Session.CurrentUser.Address)
                    {
                        meetingRecipients.Add(new MeetingRecipient(recipient));
                    }
                }
            }

            return meetingRecipients;
        }

        private void ToggleVisibility()
        {
            //    ThisRibbonCollection ribbonCollection = Globals.Ribbons[Globals.ThisAddIn.Application.ActiveInspector()];

            //    if (requestDetailsForm.OutlookItem is Microsoft.Office.Interop.Outlook.AppointmentItem)
            //    {
            //        Microsoft.Office.Interop.Outlook.AppointmentItem appointmentItem = (Microsoft.Office.Interop.Outlook.AppointmentItem)requestDetailsForm.OutlookItem;
            //        InitializeFormRegionFields(appointmentItem);

            //        {
            //            Person currrentUser;
            //            AddressEntry organizer = appointmentItem.GetOrganizer();

            //            if (organizer != null &&
            //organizer.Name == appointmentItem.Session.CurrentUser.Name)
            //            {
            //                currrentUser = new MeetingOrganizer(appointmentItem.Session.CurrentUser);
            //            }
            //            else
            //            {
            //                currrentUser = new MeetingRecipient(appointmentItem.Session.CurrentUser);
            //            }

            //            if (String.IsNullOrEmpty(txtFileName_Hidden.Text)) // Checking if hidden form field is populated, which indicates if InfoPath form data has already been submitted.
            //            {

            //                // If not organizer and non-AFS put fields in read-only and disable button.                 
            //                if (!(currrentUser is MeetingOrganizer) && currrentUser.AccountType != UserType.AFS)
            //                {
            //                    DisableFormControls();
            //                    ribbonCollection.Ribbon.btnUploadToSharepoint.Enabled = false;
            //                }
            //            }
            //            else // Form has been submitted already. Lock-down form fields and button.
            //            {
            //                DisableFormControls();
            //                ribbonCollection.Ribbon.btnUploadToSharepoint.Enabled = false;
            //            }
            //        }
            //    }
        }
    }
}
